#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int server_sock;
    int client_sock;
    // 1.socket
    if ((server_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
        error_handling("socket() error");
    if ((client_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
        error_handling("socket() error");

    char message[BUFSIZE];

    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    
    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]);
        exit(1);
    }
/*
    详见chapter7 RESUEADDR选项解决timewait问题
    int option = 1;
    int optlen = sizeof(option);
    setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&option, optlen);
*/
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    // 2.bind
    if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) 
        error_handling("bind() error");
    
    // 3.listen
    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");
    
    FILE *read_fd = fdopen(client_sock, "r");
    FILE *write_fd = fdopen(client_sock, "w");

    // 4.accept
    for (int i = 0; i < 5; i++) {
        socklen_t client_addr_size = sizeof(client_addr);
        client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &client_addr_size);
        if (client_sock == -1)
            error_handling("accept() error");
        else
            printf("connected client %d\n", i + 1);
        char buf[BUFSIZE] = {0};
        fgets(buf, BUFSIZE - 1, read_fd);
        fputs(buf, write_fd);
        printf("xxx %d\n", i + 1);
        close(client_sock);
    }
    close(server_sock);
    return 0;
}